<?php

namespace apiend\modules\user\controllers;

use Yii;
use apiend\components\Controller;
use apiend\modules\user\models\AddressForm;
use apiend\modules\user\models\AddressSearch;

/**
 * 用户收件地址接口
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class AddressController extends Controller {

    /**
     * @inheritdoc
     */
    protected function verbs() {
        return [
            '*' => ['POST'],
            'index' => ['GET'],
        ];
    }

    /**
     * @inheritdoc
     */
    protected function rules() {
        return [
            [
                'allow' => true,
                'roles' => ['@'],
            ],
        ];
    }

    /**
     * 用户收件地址列表
     * @return mixed
     */
    public function actionIndex() {
        $model = new AddressSearch();
        $model->user_id = $this->uid;
        return $model->search();
    }

    /**
     * 创建地址
     * @return mixed
     */
    public function actionCreate() {
        $model = new AddressForm();
        $model->user_id = $this->uid;
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('参数错误');
        }
        return $model->save();
    }

    /**
     * 维护地址
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = new AddressForm($id);
        $model->user_id = $this->uid;
        if (!$model->load(Yii::$app->request->post(), '')) {
            parent::error('参数错误 ');
        }
        return $model->save();
    }

    /**
     * 删除地址
     * @return mixed
     */
    public function actionDelete($id) {
        $model = AddressSearch::findOrFail($id);
        if ($model->user_id !== $this->uid) {
            parent::error('非法请求！');
        }
        if (!$model->delete()) {
            parent::error('地址删除失败');
        }
        return true;
    }

    /**
     * 设为默认地址
     * @return mixed
     */
    public function actionDefault($id) {
        $model = AddressSearch::findOrFail($id);
        if ($model->user_id !== $this->uid) {
            parent::error('非法请求！');
        }
        $model->is_default = AddressSearch::IS_DEFAULT_YES;
        if (!$model->save()) {
            parent::error('默认地址设置失败');
        }
        AddressSearch::updateAll(['is_default' => AddressSearch::IS_DEFAULT_NO], [
            'and',
            ['user_id' => $this->uid],
            ['!=', 'id', $model->id]
        ]);
        return true;
    }

}
